<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link	   http://jvitals.com
 * @since	  File available since initial release
 */
class AEmailProcessorHelper {
	
	public $data;
	public $userId;
	public $name;
	public $username;
	public $email;
	public $forumId;
	public $topicId;
	public $postId;
	public $itemId;
	public $sitename;
	public $siteurl;
	public $title;
	public $message;
	public $poster;
	public $postpage;
	public $num_replies;
	
	function __construct() {
		$this->data = '';
		$this->userId = '';
		$this->name = '';
		$this->username = '';
		$this->email = '';
		$this->forumId = '';
		$this->topicId = '';
		$this->postId = '';
		$this->itemId = '';
		$this->sitename = '';
		$this->siteurl = '';
		$this->title = '';
		$this->message = '';
		$this->poster = '';
		$this->postpage = '';
		$this->num_replies = 0;
	}
	
	static function & getInstance() {
		static $inst;
		if (!isset($inst)) {
			$inst = new AEmailProcessorHelper();
		}
		return $inst;
	}
	
	function Process() {
		//$this->_processPlugins();
		$this->_processUsersTags();
		$this->_processLinks();
		return $this->data;
	}
	
	function setData($externalData='') {
		$this->data= $externalData;
	}
	
	function setUserId($externalData='') {
		$this->userId= $externalData;
	}
	
	function setName($externalData='') {
		$this->name= $externalData;
	}
	
	function setUserName($externalData='') {
		$this->username= $externalData;
	}
	
	function setEmail($externalData='') {
		$this->email= $externalData;
	}
	
	function setForumId($externalData='') {
		$this->forumId= $externalData;
	}
	
	function setTopicId($externalData='') {
		$this->topicId= $externalData;
	}
	
	function setPostId($externalData='') {
		$this->postId= $externalData;
	}
	
	function setItemId($externalData='') {
		$this->itemId= $externalData;
	}
	
	function setSiteName($externalData='') {
		$this->sitename= $externalData;
	}
	
	function setSiteURL($externalData='') {
		$this->siteurl= $externalData;
	}
	
	function setTitle($externalData='') {
		$this->title= $externalData;
	}
	
	function setMessage($externalData='') {
		$this->message= $externalData;
	}
	
	function setPoster($externalData='') {
		$this->poster= $externalData;
	}
	
	function setPostPage($externalData='') {
		$this->postpage = $externalData;
	}
	
	function setNumReplies($num_replies = 0) {
		$this->num_replies = $num_replies;
	}
	
	function getData() {
		return $this->data;
	}
	
	function getPlainData() {
		return  $this->htmlToText($this->data);
	}

	function _processPlugins() {
			/*
			 * Process the prepare content plugins
			 */
		JPluginHelper::importPlugin('content');
		$dispatcher	=& JDispatcher::getInstance();
		$results = $dispatcher->trigger('onPrepareContent', array (& $this->data));
		$this->data = $results;
	}
	
	function _processLinks() {
		$this->data = $this->_convertInternalLink($this->data);
		$this->data = $this->_convertUnsubscribeLink($this->data, $this->topicId, $this->itemId, (0 == (int) $this->userId ? $this->email : false));
		$this->data = $this->_convertForumLink($this->data, $this->forumId, $this->itemId);
		$this->data = $this->_convertTopicLink($this->data, $this->topicId, $this->itemId);
		$this->data = $this->_convertModerationLink($this->data, $this->topicId, $this->itemId);
		$this->data = $this->_convertPostLink($this->data, $this->topicId, $this->postId, $this->postpage, $this->itemId);
		$this->data = $this->_convertAgoraLink($this->data, $this->itemId);
		$this->data = $this->_convertAgoraProfileLink($this->data, $this->itemId);
		$this->data = $this->_convertSiteLink($this->data, $this->siteurl);
		$this->data = $this->_convertBackgroundTags($this->data);
	}
	
	function _processUsersTags() {
		$isNew = (2 > (int) $this->num_replies);
		$isGuest = (0 == (int) $this->userId);
		$this->data = $this->_convertBlock($this->data, JText::_('CC_AGORA_TAG_NEW'), $isNew);
		$this->data = $this->_convertBlock($this->data, JText::_('CC_AGORA_TAG_NEW'), !$isNew, '!');
		$this->data = $this->_convertBlock($this->data, JText::_('CC_AGORA_TAG_GUEST'), $isGuest);
		$this->data = $this->_convertBlock($this->data, JText::_('CC_AGORA_TAG_GUEST'), !$isGuest, '!');
		$this->data = $this->_convertPosterUserName($this->data, $this->poster);
		$this->data = $this->_convertMessage($this->data, $this->message);
		$this->data = $this->_convertSiteName($this->data, $this->sitename);
		$this->data = $this->_convertTitle($this->data, $this->title);
		$this->data = $this->_convertName($this->data, $this->name);
		$this->data = $this->_convertUserName($this->data, $this->username);
		$this->data = $this->_convertEmail($this->data, $this->email);
	}
	
	/**
	 * removes segments based on conditional tags
	 * 
	 * @param string $html
	 * @param string $tag
	 * @param bool $bool
	 * @param string $pre
	 */
	function _convertBlock($html, $tag, $bool, $pre = '') {
		if (empty($tag) || false === stripos($html, $tag)) return $html;
		// safe tags :)
		$tag = preg_quote($pre.$tag);
		if ($bool) {
			$html = preg_replace("/\[\/?$tag\]/i", '', $html);
		} else {
			$html = preg_replace("/\[$tag\].*?\[\/$tag\]/i", '', $html);
		}
		return $html;
	}
	
	// function to create the "unsubscribe link"
	function _convertUnsubscribeLink($html_content, $topicId, $itemId, $email = false) {
		$mod_html_content=null;
		$unsubscribelink = JText::_( 'CC_AGORA_TAG_UNSUBSCRIBE' );
		$url='<a href="'.JRoute::_(JURI::root().'index.php?option=com_agora&task=topic&action=unsubscribe&' . (!empty($email) ? 'email='.urlencode($email).'&' : '') . 'id='.$topicId.'&Itemid='.$itemId).'">'.JText::_( 'CC_AGORA_TAG_UNSUBSCRIBE_LINK' ).'</a>';
		$mod_html_content=str_replace("[".$unsubscribelink."]" , $url,$html_content);
		return $mod_html_content;
	}
	
	function _convertSiteLink($html_content,  $sitelink) {
		$mod_html_content=null;
		$tagname = JText::_( 'CC_AGORA_TAG_SITE' );
		$url='<a href="'.JRoute::_($sitelink).'">'.JText::_( 'CC_AGORA_TAG_SITE_LINK' ).'</a>';
		$mod_html_content=str_replace("[".$tagname."]" , $url,$html_content);
		return $mod_html_content;
	}
	
	function _convertAgoraLink($html_content,  $itemId) {
		$mod_html_content=null;
		$tagname = JText::_( 'CC_AGORA_TAG' );
		$url='<a href="'.JRoute::_(JURI::root().'index.php?option=com_agora&Itemid='.$itemId).'">'.JText::_( 'CC_AGORA_TAG_LINK' ).'</a>';
		$mod_html_content=str_replace("[".$tagname."]" , $url,$html_content);
		return $mod_html_content;
	}
	
	function _convertAgoraProfileLink($html_content,  $itemId) {
		$mod_html_content=null;
		$tagname = JText::_( 'CC_AGORA_TAG_PROFILE' );
		$url='<a href="'.JRoute::_(JURI::root().'index.php?option=com_agora&task=profile&Itemid='.$itemId).'">'.JText::_( 'CC_AGORA_TAG_PROFILE_LINK' ).'</a>';
		$mod_html_content=str_replace("[".$tagname."]" , $url,$html_content);
		return $mod_html_content;
	}
	
	function _convertForumLink($html_content, $forumId, $itemId) {
		$mod_html_content=null;
		$tagname = JText::_( 'CC_AGORA_TAG_FORUM' );
		$url='<a href="'.JRoute::_(JURI::root().'index.php?option=com_agora&task=forum&id='.$forumId.'&Itemid='.$itemId).'">'.JText::_( 'CC_AGORA_TAG_FORUM_LINK' ).'</a>';
		$mod_html_content=str_replace("[".$tagname."]" , $url,$html_content);
		return $mod_html_content;
	}
	
	function _convertTopicLink($html_content, $topicId, $itemId) {
		$mod_html_content=null;
		$tagname = JText::_( 'CC_AGORA_TAG_TOPIC' );
		$url='<a href="'.JRoute::_(JURI::root().'index.php?option=com_agora&task=topic&id='.$topicId.'&Itemid='.$itemId).'">'.JText::_( 'CC_AGORA_TAG_TOPIC_LINK' ).'</a>';
		$mod_html_content=str_replace("[".$tagname."]" , $url,$html_content);
		return $mod_html_content;
	}
	
	function _convertModerationLink($html_content, $topicId, $itemId) {
		$mod_html_content=null;
		$tagname = JText::_( 'CC_AGORA_TAG_MODERATION' );
		
		if ((int)$this->num_replies > 1) {
			$url = '<a href="' .JRoute::_(JURI::root().'index.php?option=com_agora&task=moderation&action=show_posts&Itemid='.$itemId).'">'.JText::_( 'CC_AGORA_TAG_MODERATION_POSTS_LINK' ).'</a>';
		} else {
			$url = '<a href="' .JRoute::_(JURI::root().'index.php?option=com_agora&task=moderation&action=show_topics&Itemid='.$itemId).'">'.JText::_( 'CC_AGORA_TAG_MODERATION_TOPICS_LINK' ).'</a>';
		}
		$mod_html_content=str_replace("[".$tagname."]" , $url,$html_content);
		
		return $mod_html_content;
	}
	
	function _convertPostLink($html_content, $topicId, $postId, $postpage, $itemId) {
		$mod_html_content=null;
		$tagname = JText::_( 'CC_AGORA_TAG_POST' );
		$url= '<a href="'.JRoute::_(JURI::root().'index.php?option=com_agora&task=topic&id='.$topicId.'&p='.$postpage.'&Itemid='.$itemId.'#p'.$postId).'">'.JText::_( 'CC_AGORA_TAG_POST_LINK' ).'</a>';
		$mod_html_content=str_replace("[".$tagname."]" , $url,$html_content);
		return $mod_html_content;
	}
	
	// function to generate the site name
	function _convertMessage($html_content,$message) {
		global $mainframe;
		$tagname = JText::_( 'CC_AGORA_TAG_MESSAGE' );
		$mod_html_content=null;
		$mod_html_content=str_replace('['.$tagname.']', $message, $html_content);
		return $mod_html_content;
	}
	
	// function to generate the site name
	function _convertSiteName($html_content,$sitename) {
		global $mainframe;
		$tagname = JText::_( 'CC_AGORA_TAG_SITENAME' );
		$mod_html_content=null;
		$mod_html_content=str_replace('['.$tagname.']', $sitename, $html_content);
		return $mod_html_content;
	}
	
	// function to generate the site name
	function _convertTitle($html_content, $title) {
		global $mainframe;
		$tagname = JText::_( 'CC_AGORA_TAG_TITLE' );
		$mod_html_content=null;
		$mod_html_content=str_replace('['.$tagname.']', $title, $html_content);
		return $mod_html_content;
	}
	
	// function to generate the name
	function _convertName($html_content,$subscriberName) {
		global $mainframe;
		$tagname = JText::_( 'CC_AGORA_TAG_NAME' );
		$mod_html_content=null;
		$mod_html_content=str_replace('['.$tagname.']', $subscriberName, $html_content);
		return $mod_html_content;
	}
	
	// function to generate the username
	function _convertUserName($html_content,$subscriberUserName) {
		global $mainframe;
		$tagname = JText::_( 'CC_AGORA_TAG_USERNAME' );
		$mod_html_content=null;
		$mod_html_content=str_replace('['.$tagname.']', $subscriberUserName, $html_content);
		return $mod_html_content;
	}
	
	// function to generate the username
	function _convertPosterUserName($html_content,$subscriberUserName) {
		global $mainframe;
		$tagname = JText::_( 'CC_AGORA_TAG_POSTER_USERNAME' );
		$mod_html_content=null;
		$mod_html_content=str_replace('['.$tagname.']', $subscriberUserName, $html_content);
		return $mod_html_content;
	}
	// function to generate the username
	function _convertEmail($html_content,$subscriberEmail) {
		global $mainframe;
		$tagname = JText::_( 'CC_AGORA_TAG_EMAIL' );
		$mod_html_content=null;
		$mod_html_content=str_replace('['.$tagname.']', $subscriberEmail, $html_content);
		return $mod_html_content;
	}
	
	// function to convert the images used in a background tag
	// TODO: I think this breaks if your background in a table is a color
	function _convertBackgroundTags($html_content) {
		global $mainframe;
		$mod_html_content=null;
		// get the URL for our site so we can build absolute URLs
		$imgPathPrefix=JRoute::_ (JURI::root());
		// define the search tag to search for
		$imgTag='background="'.$imgPathPrefix;
		// store the modified html content in a local variable
		$mod_html_content=str_replace('background="',$imgTag,$html_content);
		// return the modified content, image tags are now absolute for use in the newslettter
		return $mod_html_content;
	}
	
	function _convertInternalLink($body) {
		global $mainframe;
		$body = preg_replace('#src[ ]*=[ ]*\"(?!https?://)(?:\.\./|\./|/)?#','src="'.JRoute::_(JURI::root()).'/',$body);
		$body = preg_replace('#href[ ]*=[ ]*\"(?!https?://)(?:\.\./|\./|/)?#','href="'.JRoute::_(JURI::root()).'/',$body);
		return $body;
	}
	
	function htmlToText($textonly) {
		$textonly = str_replace(array('<p>', '<P>'), "", $textonly);
		$textonly =preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $textonly);
		$returns = array('<br>', '<br/>', '<br />', '<br >','<BR >', '<BR>', '<BR/>', '<BR />', '</p>', '</P>', '<p />', '<p/>', '<P />', '<P/>', '</h3>', '</H3>', '</h4>', '</H4>', '</h5>', '</H5>', '</h6>', '</H6>', '</h1>', '</H1>', '</h2>', '</H2>');
		/* $returns = array('/<(?:br|p)\ +?\/?>/i', '/<\/(?:p|h[1-6])>/i'); // < this is better ... ^ this sucks */
		$textonly = str_replace($returns, "\n", $textonly);
		$textonly = preg_replace('/<a href="([^"]*)"[^>]*>([^<]*)<\/a>/i','${2} ( ${1} )', $textonly);
		$textonly = preg_replace('/<head>.*<\/head>/i', '', $textonly);
		$textonly = preg_replace('~&#x([0-9a-f]+);~ei', chr(hexdec("\\1")), $textonly);
		$textonly = preg_replace('~&#([0-9]+);~e', chr("\\1"), $textonly);
		$trans_tbl = get_html_translation_table(HTML_ENTITIES);
		$trans_tbl = array_flip($trans_tbl);
		$textonly = strtr($textonly, $trans_tbl);
		$textonly = strip_tags($textonly);
		return $textonly;
	}
	
}


